package com.mtons.mblog.modules.repository;

import com.mtons.mblog.modules.entity.Tag;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

/**
 * @author : langhsu
 */
@Repository
public interface TagRepository extends JpaRepository<Tag, Long>, JpaSpecificationExecutor<Tag> {
    Tag findByName(String name);

    @Modifying
    @Query("update Tag set posts = posts - 1 where id in (:ids) and posts > 0")
    int decrementPosts(@Param("ids") Collection<Long> ids);
    
    @Query("from Tag t where t.id in (select DISTINCT tagId from PostTag where postId in (select id from Post where status = 0))")
    Page<Tag> findAbleTags(Pageable pageable);
    
    @Query("from Tag t where t.id in (select DISTINCT tagId from PostTag where postId in (select id from Post where status = 0))")
    List<Tag> findAllHavePost();
}
